﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace AutoShutdownWindows
{
    public class configure
    {
        private configure()
        {

        }

        private Dictionary<string, CustomSections> _customSections;
        public Dictionary<string, CustomSections> CustomSections
        {
            get { return _customSections; }
        }

        private string _path;
        public string Path
        {
            get { return _path; }
        }

        public static configure Load(string path)
        {
            configure config = new configure();
            config._path = path;          

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.XmlResolver = null;            
            xmldoc.Load(path);            

            config._customSections = new Dictionary<string, CustomSections>();

            XmlNodeList nodes = xmldoc.SelectNodes("//customSection");

            int index = 0;

            for (; index < nodes.Count; index++)
            {
                XmlNode node = nodes[index];
                CustomSections custom = new CustomSections();
                custom.StartTime = node.Attributes["starttime"].Value;
                custom.Useable = (node.Attributes["useable"].Value + "").Equals("true") ? true : false;
                var n = SelectSingleNode(node, "shutdown", "useable", "true");
                string type = n.Attributes["type"].Value;
                string text = n.InnerText.Trim('\r').Trim();
                custom.Shutdown = new Shutdown() { Type = type, Text = text };
                custom.Node = (XmlElement)n;
                config._customSections.Add("customSection" + (index + 1), custom);
            }

            return config;
        }

        public static XmlNode SelectSingleNode(XmlNode node, string name,string attrname,string attrvalue)
        {
            XmlNode val = null;
            foreach (XmlNode n in node.ChildNodes)
            {
                if (n.Name.Equals(name,
                    StringComparison.InvariantCultureIgnoreCase))
                {
                    if (n.Attributes[attrname] != null
                        && n.Attributes[attrname].Value.Equals(attrvalue))
                    {
                        val = n;
                        break;
                    }
                }
            }
            return val;
        }

        public static XmlNode SelectSingleNode(XmlNode node, string name)
        {
            XmlNode val = null;
            foreach (XmlNode n in node.ChildNodes)
            {
                if (n.Name.Equals(name,
                    StringComparison.OrdinalIgnoreCase))
                {
                    val = n;
                    break;
                }
            }
            return val;
        }

    }
}
